//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package api_collection_api_serv

import (
	"context"

	"atomgit.com/openlinksaas/api-server/api_common"
	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/api_coll_dao"
	"atomgit.com/openlinksaas/api-server/dao/fs_dao"
	"atomgit.com/openlinksaas/api-server/dao/project_entry_dao"
	"atomgit.com/openlinksaas/api-server/utils"
	"atomgit.com/openlinksaas/proto-gen-go.git/api_collection_api"
	"atomgit.com/openlinksaas/proto-gen-go.git/project_entry_api"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/mongo"
)

func (apiImpl *ApiCollectionApiImpl) CreateRpc(ctx context.Context, req *api_collection_api.CreateRpcRequest) (*api_collection_api.CreateRpcResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &api_collection_api.CreateRpcResponse{
			Code:   api_collection_api.CreateRpcResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	projectItem, _, _, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &api_collection_api.CreateRpcResponse{
			Code:   api_collection_api.CreateRpcResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
		}, nil
	} else if err == utils.ErrNoRole {
		return &api_collection_api.CreateRpcResponse{
			Code:   api_collection_api.CreateRpcResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	} else if err != nil {
		return nil, err
	}
	if projectItem.Closed {
		return &api_collection_api.CreateRpcResponse{
			Code:   api_collection_api.CreateRpcResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	//检查文件是否存在
	exist, err := fs_dao.FsFileDao.Exist(ctx, projectItem.ApiCollFsId, req.ProtoFileId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &api_collection_api.CreateRpcResponse{
			Code:   api_collection_api.CreateRpcResponse_CODE_NO_FILE,
			ErrMsg: "协议文件不存在",
		}, nil
	}

	apiCollId := uuid.NewString()

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = api_coll_dao.GrpcExtraDao.Insert(sessCtx, &api_coll_dao.GrpcExtraInfoDbItem{
			ApiCollId:   apiCollId,
			ProtoFileId: req.ProtoFileId,
			Secure:      req.Secure,
		})
		if err != nil {
			return nil, err
		}

		return &api_collection_api.CreateRpcResponse{
			Code:      api_collection_api.CreateRpcResponse_CODE_OK,
			ApiCollId: apiCollId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*api_collection_api.CreateRpcResponse), nil
}

func (apiImpl *ApiCollectionApiImpl) GetRpc(ctx context.Context, req *api_collection_api.GetRpcRequest) (*api_collection_api.GetRpcResponse, error) {
	emptyInfo := &api_collection_api.GrpcExtraInfo{}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &api_collection_api.GetRpcResponse{
			Code:      api_collection_api.GetRpcResponse_CODE_WRONG_SESSION,
			ErrMsg:    "会话不存在",
			ExtraInfo: emptyInfo,
		}, nil
	}
	_, _, _, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &api_collection_api.GetRpcResponse{
			Code:      api_collection_api.GetRpcResponse_CODE_NO_PROJECT,
			ErrMsg:    "项目不存在",
			ExtraInfo: emptyInfo,
		}, nil
	} else if err == utils.ErrNoRole {
		return &api_collection_api.GetRpcResponse{
			Code:      api_collection_api.GetRpcResponse_CODE_NO_PERMISSION,
			ErrMsg:    "没有权限",
			ExtraInfo: emptyInfo,
		}, nil
	} else if err != nil {
		return nil, err
	}

	infoItem, err := api_coll_dao.GrpcExtraDao.Get(ctx, req.ApiCollId)
	if err != nil {
		return &api_collection_api.GetRpcResponse{
			Code:      api_collection_api.GetRpcResponse_CODE_NO_GRPC_API,
			ErrMsg:    "GRPC定义不存在",
			ExtraInfo: emptyInfo,
		}, nil
	}
	return &api_collection_api.GetRpcResponse{
		Code:      api_collection_api.GetRpcResponse_CODE_OK,
		ExtraInfo: infoItem.ToGrpcExtraInfo(),
	}, nil
}

func (apiImpl *ApiCollectionApiImpl) UpdateRpc(ctx context.Context, req *api_collection_api.UpdateRpcRequest) (*api_collection_api.UpdateRpcResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &api_collection_api.UpdateRpcResponse{
			Code:   api_collection_api.UpdateRpcResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	projectItem, _, roleItem, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &api_collection_api.UpdateRpcResponse{
			Code:   api_collection_api.UpdateRpcResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
		}, nil
	} else if err == utils.ErrNoRole {
		return &api_collection_api.UpdateRpcResponse{
			Code:   api_collection_api.UpdateRpcResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	} else if err != nil {
		return nil, err
	}
	if projectItem.Closed {
		return &api_collection_api.UpdateRpcResponse{
			Code:   api_collection_api.UpdateRpcResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	//检查信息是否存在
	entryItem, err := project_entry_dao.EntryDao.Get(ctx, req.ApiCollId, req.ProjectId)
	if err != nil {
		return &api_collection_api.UpdateRpcResponse{
			Code:   api_collection_api.UpdateRpcResponse_CODE_NO_GRPC_API,
			ErrMsg: "GRPC定义不存在",
		}, nil
	}
	if entryItem.EntryType != uint32(project_entry_api.ENTRY_TYPE_ENTRY_TYPE_API_COLL) {
		return &api_collection_api.UpdateRpcResponse{
			Code:   api_collection_api.UpdateRpcResponse_CODE_NO_GRPC_API,
			ErrMsg: "GRPC定义不存在",
		}, nil
	}

	hasUpdatePerm := api_common.CheckEntryCanUpdate(sessionItem, projectItem, roleItem, entryItem)

	if !hasUpdatePerm {
		return &api_collection_api.UpdateRpcResponse{
			Code:   api_collection_api.UpdateRpcResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	//检查文件是否存在
	exist, err := fs_dao.FsFileDao.Exist(ctx, projectItem.ApiCollFsId, req.ProtoFileId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &api_collection_api.UpdateRpcResponse{
			Code:   api_collection_api.UpdateRpcResponse_CODE_NO_FILE,
			ErrMsg: "协议文件不存在",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = api_coll_dao.GrpcExtraDao.Update(sessCtx, req.ApiCollId, req.ProtoFileId, req.Secure)
		if err != nil {
			return nil, err
		}
		return &api_collection_api.UpdateRpcResponse{
			Code: api_collection_api.UpdateRpcResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*api_collection_api.UpdateRpcResponse), nil
}
